package com.kopi.Sendungsverfolgung;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

public class Helper {

	private static HttpClient httpClient = new DefaultHttpClient();
	private static HttpContext localContext = new BasicHttpContext();

	public static String GetHtml(String url, boolean cleanHtml) {
		StringBuffer sb = new StringBuffer();

		HttpGet httpGet = new HttpGet(url);
		HttpResponse response = null;
		try {
			response = httpClient.execute(httpGet, localContext);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(response
					.getEntity().getContent()));
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append("\r\n" + line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		if (cleanHtml)
			return CleanHtml(sb.toString());

		return sb.toString();
	}

	public static String CleanHtml(String html) {
		Pattern pattern = Pattern.compile("[\\s]{2}");
		Matcher m = pattern.matcher(html);
		html = m.replaceAll("");
		html = html.replace("\n", "").replace("\r", "").replace("\t", "").replace("&nbsp;", "");

		return html;
	}
}